﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Linq;

namespace Fireball.OpenXML.Word
{
    /// <summary>
    /// Line Spacing Rule
    /// </summary>
    public enum LineSpacingRule
    {
        /// <summary>
        /// Automatically Determined Line Height
        /// </summary>
        auto,
        /// <summary>
        /// Exact Line Height
        /// </summary>
        exact,
        /// <summary>
        /// Minimum Line Height
        /// </summary>
        atLeast
    }

    /// <summary>
    /// 
    /// </summary>
    public sealed class ParagraphSpacing : OpenXMLEntity
    {
        public decimal? After
        {
            get;
            set;
        }

        public decimal? Line
        {
            get;
            set;
        }

        [DefaultValue(LineSpacingRule.auto)]
        public LineSpacingRule Rule
        {
            get;
            set;
        }

        private void ParseInternal(XElement xElement)
        {
            if (xElement.Name.LocalName != "spacing")
            {
                throw new Exception("Invalid tag for paragraph Spacing");
            }

            var after = xElement.Attribute(NS.WM + "after");

            if (after != null)
                this.After = Convert.ToDecimal(after.Value);

            var rule = xElement.Attribute(NS.WM + "lineRule");

            if (rule != null)
                this.Rule = (LineSpacingRule)Enum.Parse(typeof(LineSpacingRule), rule.Value, true);

            var line = xElement.Attribute(NS.WM + "line");

            if (line != null)
                this.Line = Convert.ToDecimal(line.Value);
        }

        public static ParagraphSpacing Parse(XElement xElement)
        {
            ParagraphSpacing p = new ParagraphSpacing();
            p.ParseInternal(xElement);
            return p;
        }

        public override System.Xml.Linq.XContainer ToXml()
        {
            XElement xRoot = new XElement(NS.WM + "spacing");

            if (this.After != null)
            {
                xRoot.Add(new XAttribute(NS.WM + "after", this.After.Value));
            }

            if (this.Line != null)
            {
                xRoot.Add(new XAttribute(NS.WM + "line", this.Line.Value));
            }

            xRoot.Add(new XAttribute(NS.WM + "lineRule", this.Rule.ToOffice()));

            return xRoot;
        }
    }
}
